package com.shujia.dws

import com.shujia.common.utils.SparkMain
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.{DataFrame, SaveMode, SparkSession}

object DwsCityTouristMskDay extends SparkMain {
  override def run(spark: SparkSession): Unit = {
    import spark.implicits._
    import org.apache.spark.sql.functions._

    // 分别加载 用户画像维表 行政区域配置维表 位置数据融合表
    val userTagDF: DataFrame = spark.table("dim.dim_usertag_msk_d")
      .where($"day_id" === dayId)
      // 将需要用到的列查出来
      .select(
        $"mdn"
        , $"resi_grid_id"
        , $"resi_county_id"
      )

    val adminCodeDF: DataFrame = spark.table("dim.dim_admincode")
      .select(
        $"city_id"
        , $"county_id"
      )

    val mergeDF: DataFrame = spark.table("dwi.dwi_res_regn_mergelocation_msk_d").where($"day_id" === dayId)

    /**
     * 市游客：
     * 1、停留时间超过3小时
     * 2、出行距离大于100KM
     */

    val cityTouristDF: DataFrame = mergeDF
      // 关联行政区域配置表 获取city_id
      .join(adminCodeDF, List("county_id"), "inner")
      .select($"mdn", $"start_date", $"end_date", $"city_id", $"grid_id")
      // 计算停留时间
      .withColumn("min_start_date", min($"start_date") over Window.partitionBy($"mdn", $"city_id"))
      .withColumn("max_end_date", max($"end_date") over Window.partitionBy($"mdn", $"city_id"))
      .withColumn("d_stay_time", diffTime($"min_start_date", $"max_end_date"))
      .where($"d_stay_time" > 3 * 60 * 60)
      // 关联用户画像表 获取用户居住地的网格id 以及 居住地的区县id
      .join(userTagDF, List("mdn"), "inner")
      .select($"mdn", $"city_id" as "d_city_id", $"grid_id", $"d_stay_time", $"resi_grid_id", $"resi_county_id")
      // 计算用户居住地到目的地的距离
      .withColumn("distance", calculateLengthWithGrid($"grid_id", $"resi_grid_id"))
      // 统计每个用户从每个居住地到每座城市的最远距离作为出行距离
      .withColumn("d_max_distance", max($"distance") over Window.partitionBy($"mdn", $"d_city_id", $"resi_county_id"))
      .where($"d_max_distance" > 100 * 1000)
      // 整理数据
      .select(
        $"mdn"
        , $"resi_county_id" as "source_county_id"
        , $"d_city_id"
        , $"d_stay_time"
        , $"d_max_distance"
      )
      .distinct()

    // 保存数据
    cityTouristDF
      .write
      .format("csv")
      .option("sep", ",")
      .mode(SaveMode.Overwrite)
      .save(s"/daas/motl/dws/dws_city_tourist_msk_d/day_id=$dayId")

    spark.sql(
      s"""
         |alter table dws.dws_city_tourist_msk_d add if not exists partition(day_id='$dayId')
         |""".stripMargin)

  }

  /**
   * 提交命令：
   * spark-submit --master yarn-client --conf spark.sql.shuffle.partitions=10 --class com.shujia.dws.DwsCityTouristMskDay --jars common-1.0.jar dws-1.0.jar 20230105
   */
}
